package com.iot08.api.service;

import com.alibaba.fastjson.JSONObject;
import com.iot08.api.response.ChatMessageLastResp;
import com.iot08.api.response.VimMemberResp;
import com.iot08.api.utils.TimeUtils;
import com.iot08.api.utils.buckettool.BaseBucketTool;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.app.SingleChatGroupMessage;
import com.iot08.common.entity.app.VipMember;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseMap;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 单聊消息
 * @time: 2021-10-30 17:33
 * @author: Weichao
 * @version 1.0
 */
@Slf4j
@Service
public class SingleChatGroupMessageService extends BaseService<SingleChatGroupMessage> {

    //当前API 使用的域名
    @Value("${domain.name}")
    private String domainName;

    @Resource
    private BaseBucketTool baseBucketTool;

    @Resource
    private VipMemberService vipMemberService;

    /**
     * @param message
     * @time: 2021/1/23 12:06
     * @author: Rock
     * @version 1.0
     */
    public void add(SingleChatGroupMessage message) {
        message.setExpiryAt(DateUtil.getSystemExpiryAt());
        message.setTimestamp(DateUtil.nowTimestampToDouble());
        this.save(message);
    }

    /**
     * 根据条件查询 单聊的聊天消息
     * @param deletetime
     * @param query
     * @param num
     * @param page
     * @param sort
     * @param isWX_ios  是否是 iOS的微信(微信小程序) 需要判断把AMR 转成 MP3 调用对应的转换 接口 /getway/wxSmallProgram/getaudio/***
     * @time: 2021/1/14 11:31
     * @author: Rock
     * @version 1.0
     */
    public List<Map<String, Object>> messageQueryHandle(Double deletetime, Document query, int num, int page, int sort, boolean isWX_ios) {
        List<Map<String, Object>> datas = new ArrayList<>();

        FindIterable<Document> document = this.findDoc(query, Filters.eq("_id", sort), page, num);
        for (Document doc : document) {
            Integer type = doc.getInteger("mt");
            Double time = doc.getDouble("t");
            if (time != null && time > deletetime) {
//            if (time != null) {
                JSONObject temp = new JSONObject();
                temp.put("id", doc.get("_id").toString());
                temp.put("senderID", doc.get("s"));
                temp.put("senderType", doc.get("st"));
                temp.put("type", type);
                if(ObjectUtils.isNotEmpty(doc.get("chatReportTime")))
                {
                    temp.put("chatReportTime",doc.get("chatReportTime").toString());
                }
                if(doc.get("avator") != null){
                    temp.put("avator", doc.get("avator"));
                }
                temp.put("timestamp", doc.get("t"));
                if (doc.containsKey("openid") && doc.containsKey("relationship")) {
                    temp.put("openid", doc.get("openid"));
                    temp.put("relationship", doc.get("relationship"));
                    temp.put("relationship_image_id", doc.get("relationship_image_id"));
                }
                if (Const.INT_1.equals(type)) {
                    temp.put("content", doc.get("c"));
                } else if (new Integer(2).equals(type)) {
                    temp.put("content", baseBucketTool.getDOMAIN() + BaseBucketTool.MESSAGE_COMMON_PATH + doc.get("c"));
                } else if (new Integer(3).equals(type)) {
                    temp.put("content", baseBucketTool.getDOMAIN() + BaseBucketTool.MESSAGE_COMMON_PATH + doc.get("c"));
                    //是设备上报的 senderType == 2 && 内容包含 .amr
                    if(isWX_ios && temp.getInteger("senderType") == 2 && temp.getString("content").contains(".amr")){
                        temp.put("content", String.format("http://%s/getway/wxSmallProgram/getaudio/%s", domainName, doc.get("c").toString().replace(".amr", ".mp3")));
                    }
                    if (!StringUtil.isNumeric(doc.get("duration")) || Double.parseDouble(doc.get("duration").toString()) < 1) {
                        temp.put("duration", 1);
                    } else {
                        temp.put("duration", Double.parseDouble(doc.get("duration").toString()));
                    }
                } else if (new Integer(4).equals(type)) {
                    temp.put("content", doc.get("c"));
                    //表情包
                    temp.put("bqId", doc.get("bqId"));
                }
                datas.add(temp);
            }
        }
        return datas;
    }

    /**
     * @description 按条件查询最后一条记录
     * @author cwj
     * @param [groupid, openid]
     * @return com.iot08.api.response.ChatMessageLastResp
     * @date @time 2025/7/1 11:11
     **/
    public ChatMessageLastResp queryLastMessage(String groupid,String openid,Double deletetime){
        //查询用户是否为会员
        Query query = new Query();
        Criteria criteria = Criteria.where("i").is(groupid);
        VipMember vimMember = vipMemberService.queryVipMemberByOpenid(openid);
        if(ObjectUtils.isEmpty(vimMember)) {
            criteria.and("isExceedLimitRecord").is(1);
        }
        criteria.and("t").gt(deletetime);
        query.addCriteria(criteria);
        query.with(Sort.by(Sort.Direction.DESC, "t"));
        query.limit(1);
        ChatMessageLastResp chatMessageLastResp = mongoTemplate.findOne(query,ChatMessageLastResp.class,"single_chat_group_message");
        if(ObjectUtils.isNotEmpty(chatMessageLastResp)) {
            if(new Integer(2).equals(chatMessageLastResp.getMessageType()) || new Integer(3).equals(chatMessageLastResp.getMessageType())) {
                chatMessageLastResp.setContent(baseBucketTool.getDOMAIN() + BaseBucketTool.MESSAGE_COMMON_PATH+chatMessageLastResp.getContent());
            }
            //去掉年和秒
            chatMessageLastResp.setChatReportTime(TimeUtils.transferTimeStr(chatMessageLastResp.getChatReportTime()));
        }
        return chatMessageLastResp;
    }

}
